package edu.mju.msmservice.controller;

import edu.mju.commonutils.ReturnCode;
import edu.mju.msmservice.service.MsmService;
import edu.mju.msmservice.util.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 短信服务Controller
 * @Author: wyp
 * @Date: 2020/9/27 9:46
 */
@RestController
@RequestMapping("/edumsm/msm")
public class MsmController {

    @Autowired
    private MsmService msmService;

    /**
     * 整合Redis 短信验证码的时效性
     */
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     *  发送短信的方法
     * @param phone 手机号
     * @return json数据
     */
    @GetMapping("/send/{phone}")
    public ReturnCode sendMsm(@PathVariable String phone){
        //1.从redis取验证码，如果有，就不发送
        String code = redisTemplate.opsForValue().get(phone);
        if(!StringUtils.isEmpty(code)){
            return ReturnCode.success();
        }

        //2.如果redis没有，则发送短信

        //生成随机值，传递给阿里云发送短信
        //生成六位随机数
        code = RandomUtil.getSixBitRandom();

        //放入put集合
        Map<String,Object> param = new HashMap<>();
        param.put("code",code);

        //调用service发送短信的方法
        boolean isSend = msmService.sendMsm(param,phone);

        if(isSend){
            //发送成功，验证码存redis
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
            return ReturnCode.success();
        }else {
            return ReturnCode.fail().message("短信发送失败");
        }
    }
}
